/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.cef.repository.adaptoritem.dbprocessor;

import com.inspur.edp.cef.api.repository.DbParameter;
import com.inspur.edp.cef.api.repository.readerWriter.ICefReader;
import com.inspur.edp.cef.entity.dependenceTemp.DataValidator;
import com.inspur.edp.cef.entity.entity.EntityDataPropertyValueUtils;
import org.hibernate.jpa.TypedParameterValue;
import org.hibernate.type.StandardBasicTypes;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TemporalType;
import java.math.BigDecimal;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DbProcessor {
    public Query buildQueryManager(EntityManager entityManager, String sqlText, List<DbParameter> parameters) {
        DataValidator.checkForEmptyString(sqlText, "sqlText");
        Query query = entityManager.createNativeQuery(sqlText);
        if (parameters != null) {
            for (int i = 0; i < parameters.size(); i++) {
                DbParameter param = parameters.get(i);
                switch(param.getDataType()){
                    case VarChar:
                        buildVarcharParmeter(query, i, param);
                        break;
                    case NVarChar:
                        buildNVarcharParmeter(query, i, param);
                        break;
                    case NChar:
                        buildNCharParmeter(query, i, param);
                    case Blob:
                        buildBlobParameter(query, i, param);
                        break;
                    case Clob:
                        //TODO 后续测试DM数据库是否合适
                        buildClobParameter(query, i, param);
                        break;
                    case Int:
                        buildIntParameter(query, i, param);
                        break;
                    case Decimal:
                        buildDecimalParameter(query, i, param);
                        break;
                    case Char:
                        buildCharParameter(query, i, param);
                        break;
                    case NClob:
                        buildNClobParameter(query, i, param);
                        break;
                    case DateTime:
                        buildDateTimeParameter(query, i, param);
                        break;
                    case Date:
                        buildDateParameter(query, i, param);
                        break;
                    default:
                        throw new RuntimeException("未知的数据类型，请确认参数的类型。");
                }
            }
        }
        return query;
    }

    protected void buildVarcharParmeter(Query query, int i, DbParameter param) {
        buildParameter(query, i, param);
    }

    protected void buildNVarcharParmeter(Query query, int i, DbParameter param) {
        buildParameter(query, i, param);
    }

    protected void buildNCharParmeter(Query query, int i, DbParameter param) {
        buildParameter(query, i, param);
    }

    protected void buildBlobParameter(Query query, int i, DbParameter param) {
        buildParameter(query, i, param);
    }

    protected void buildClobParameter(Query query, int i, DbParameter param) {
        query.setParameter(i, new TypedParameterValue(StandardBasicTypes.TEXT, param.getValue()));
    }

    protected void buildIntParameter(Query query, int i, DbParameter param) {
        if(param.getValue() instanceof ArrayList){
            query.setParameter(i,param.getValue());
        }
        else {
            query.setParameter(i,new TypedParameterValue(StandardBasicTypes.INTEGER, param.getValue()));
        }
    }

    protected void buildDecimalParameter(Query query, int i, DbParameter param) {
        if(param.getValue() instanceof ArrayList){
            query.setParameter(i, param.getValue());
        }
        else {
            query.setParameter(i,new TypedParameterValue(StandardBasicTypes.BIG_DECIMAL, param.getValue()));
        }
    }

    protected void buildCharParameter(Query query, int i, DbParameter param) {
        if(param.getValue()==null){
            query.setParameter(i,new TypedParameterValue(StandardBasicTypes.STRING, param.getValue()));

        }else {
            query.setParameter(i,param.getValue()) ;
        }
    }

    protected void buildNClobParameter(Query query, int i, DbParameter param) {
        query.setParameter(i, new TypedParameterValue(StandardBasicTypes.TEXT, param.getValue()));
    }

    protected void buildDateTimeParameter(Query query, int i, DbParameter param) {
        //todo 根据Filter的Compare判断更合适?
        if(param.getValue() instanceof String){
            query.setParameter(i, param.getValue());
        }
        else {
            query.setParameter(i, (Date) param.getValue(), TemporalType.DATE);
        }
    }

    protected void buildDateParameter(Query query, int i, DbParameter param) {
        if(param.getValue() == null){
            query.setParameter(i, (Date) param.getValue(), TemporalType.DATE);
            return;
        }
        //todo 根据Filter的Compare判断更合适?
        if(param.getValue() instanceof String){
            query.setParameter(i, param.getValue());
        }
        else {
            java.sql.Date date = new  java.sql.Date(((Date) param.getValue()).getTime());
            date = java.sql.Date.valueOf(date.toString());
            query.setParameter(i, date, TemporalType.DATE);
        }
    }

    protected final void buildParameter(Query query, int i, DbParameter param) {
        query.setParameter(i,param.getValue());
    }

    public String getStringValue(ICefReader reader,String propName){
        Object obj=reader.readValue(propName);
        if (obj == null){
            return EntityDataPropertyValueUtils.getStringPropertyDefaultValue();
        }
        return obj.toString();
    }

    public Integer getIntegerValue(ICefReader reader,String propName){
        Object obj=reader.readValue(propName);
        if (obj == null)
            return null;
        Integer result = null;
        try {
            result = java.lang.Integer.valueOf(obj.toString());
        }
        catch (Exception ex){
            throw new RuntimeException("属性"+propName+"对应值["+obj.toString()+"]转换为Integer类型失败!");
        }
        return result;
    }

    public BigDecimal getBigDecimalValue(ICefReader reader, String propName){
        Object obj=reader.readValue(propName);
        if (obj == null)
            return null;
        return new BigDecimal(new BigDecimal(obj.toString()).stripTrailingZeros().toPlainString());
//        return new BigDecimal(obj.toString()).stripTrailingZeros();
    }

    public Boolean getBooleanValue(ICefReader reader, String propName){
        Object obj=reader.readValue(propName);
        if (obj == null)
            return null;
        return getBoolean(propName, obj.toString());
    }

    public final boolean getBoolean(String propName, String value){
        switch (value){
            case "0":
                return false;
            case "1":
                return true;
            default:
                throw new RuntimeException("属性["+ propName + "]存在不正确的布尔值：["+value+"]");
        }
    }

    public final boolean getBoolean(String value){
        switch (value){
            case "0":
                return false;
            case "1":
                return true;
            default:
                throw new RuntimeException("不正确的布尔值："+value);
        }
    }

    public Date getDateTimeValue(ICefReader reader,String propName){
        Object obj=reader.readValue(propName);
        if (obj == null){
            return EntityDataPropertyValueUtils.getDateTimePropertyDefaultValue();
        }
        java.util.Date dateObj = null;
        try {
            dateObj = (java.util.Date)obj;
        }
        catch (Exception ex){
            throw new RuntimeException("属性"+propName+" 对应值["+obj.toString()+"]转换为Date类型失败");
        }
        return dateObj;
    }

    public String getClobValue(ICefReader reader,String propName){
        Object obj=reader.readValue(propName);
        return getClobValue(propName, obj);
    }

    protected final String getClobValue(Object obj)
    {
        if(obj instanceof String )
        {
            return obj.toString();
        }
        else {
            try {
                return obj == null ? EntityDataPropertyValueUtils.getStringPropertyDefaultValue() : ((Clob) obj).getSubString(1L, (int) ((Clob) obj).length());
            } catch (SQLException e) {
                throw new RuntimeException("解析备注类型数据：" + obj + "失败");
            }
        }
    }

    protected final String getClobValue(String propName, Object obj)
    {
        if(obj instanceof String )
        {
            return obj.toString();
        }
        else {
            try {
                return obj == null ? EntityDataPropertyValueUtils.getStringPropertyDefaultValue() : ((Clob) obj).getSubString(1L, (int) ((Clob) obj).length());
            } catch (SQLException e) {
                throw new RuntimeException("属性" + propName + "对应数据：[" + obj + "]转换为Clob类型失败");
            }
        }
    }
    public byte[] getBlobValue(ICefReader reader,String propName)
    {
        //todo daixiugai
        Object obj=reader.readValue(propName);
        if (obj == null){
            return EntityDataPropertyValueUtils.getBinaryPropertyDefaultValue();
        }
        return (byte[])obj;
    }
}
